package top.lyc829.iot_server.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.lyc829.iot_server.bean.User;
import top.lyc829.iot_server.bean.UserFinger;
import top.lyc829.iot_server.dao.UserDao;
import top.lyc829.iot_server.dao.UserFingerDao;
import top.lyc829.iot_server.service.AccessLogService;
import top.lyc829.iot_server.service.FingerService;
import top.lyc829.iot_server.utils.MqttUtil;
import top.lyc829.iot_server.utils.Result;
import top.lyc829.iot_server.utils.UserContainer;

import javax.annotation.Resource;
import java.util.List;


@Service
public class FingerServiceImpl implements FingerService {


    @Autowired
    private UserFingerDao userFingerDao;
    @Autowired
    private AccessLogService accessLogService;
    @Autowired
    private UserDao userDao;
    @Resource
    private UserContainer userContainer;

    private MqttUtil mqttUtil;

    public FingerServiceImpl(){
        mqttUtil = MqttUtil.build();
    }

    @Override
    public String open(String content) {
        int fingerId = Integer.parseInt(content);
        UserFinger userFinger = userFingerDao.findByFingerId(fingerId);
        if (userFinger == null){
            // 开门失败
            accessLogService.add(-1,2,content,0);
            return null;
        }else {
            accessLogService.add(userFinger.getUserId(),2,content,1);
            User user = userDao.findUserById(userFinger.getUserId());
            return user.getName();
        }
    }


    @Override
    public Result deleteFingerById(int id) {

        userFingerDao.deleteById(id);

        return Result.success();
    }

    @Override
    public Result updateFinger(UserFinger finger) {
        UserFinger finger2 = userFingerDao.findByFingerId(finger.getId());
        if (finger2 == null) {
            return Result.fail("指纹不存在");
        }
        finger2.setFingerName(finger.getFingerName());
        userFingerDao.save(finger2);
        return Result.success();
    }

    @Override
    public Result addFinger(UserFinger finger) {

        User user = userDao.findUserById(finger.getUserId());
        if (user == null) {
            return Result.fail("该用户不存在");
        }

        //TODO:发送mqtt请求添加指纹
        //保存当前用户
        userContainer.setUser(user);
        userContainer.setFingerName(finger.getFingerName());
        Integer id = 0;
        if (userFingerDao.getMax() != null){
            id = userFingerDao.getMax() + 1;
        }
        mqttUtil.publish("/client/add_finger",id+"");

        return Result.success();
    }

    @Override
    public Result getFingers(int id) {

        List<UserFinger> userFingers = userFingerDao.findUserFingersByUserId(id);

        return Result.success(userFingers);
    }

}
